import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Like, Repository } from 'typeorm';
// import BaseMaterial from '@main/entities/service/admin/base/base-material.entity';
import GatherAdjustment from '@main/entities/service/admin/gather/gather-adjustment.entity';
import GatherAdjustmentProcess from '@main/entities/service/admin/gather/gather-adjustment-process.entity';
import GatherInterface from '@main/entities/service/admin/gather/gather-interface.entity';
import GatherInterfaceBtn from '@main/entities/service/admin/gather/gather-interface-btn.entity';
import GatherMachineUnit from '@main/entities/service/admin/gather/gather-machine-unit.entity';
import { ApiException } from '@main/common/exceptions/api.exception';
// import { app } from 'electron';
import { isEmpty } from 'lodash';
// import path from 'path';
// import * as fs from 'fs';
@Injectable()
export class GatherAdjustmentService {
  constructor(
    @InjectRepository(GatherAdjustment)
    private adjustmentRepository: Repository<GatherAdjustment>,
    @InjectRepository(GatherAdjustmentProcess)
    private adjustmentProcessRepository: Repository<GatherAdjustmentProcess>,
    @InjectRepository(GatherInterface)
    private interfaceRepository: Repository<GatherInterface>,
    @InjectRepository(GatherInterfaceBtn)
    private interfaceBtnRepository: Repository<GatherInterfaceBtn>,
    @InjectRepository(GatherMachineUnit)
    private machineUnitRepository: Repository<GatherMachineUnit>
  ) {}

  async list() {
    return await this.adjustmentRepository.find();
  }

  /**
   * 罗列所有配置
   */
  async page(data) {
    const { pageSize, pageNum, entity = {} } = data;

    const { machineCode } = entity;

    return await this.adjustmentRepository.findAndCount({
      where: {
        machineCode: Like(`%${machineCode}%`),
      },
      order: {
        id: 'ASC',
      },
      take: pageSize,
      skip: (pageNum - 1) * pageSize,
    });
  }

  /**
   * 新增
   */
  async add(data, user) {
    await this.adjustmentRepository.insert({
      ...data,
      createName: user.nickName,
      createUserName: user.userName,
      updateName: user.nickName,
      updateUserName: user.userName,
    });
  }

  /**
   * 更新
   */
  async update(data, user) {
    const { id, machineCode, remark, adjustmentProcessCode } = data;

    await this.adjustmentRepository.update(
      { id },
      {
        machineCode,
        adjustmentProcessCode,
        remark,
        updateName: user.nickName,
        updateUserName: user.userName,
      }
    );
  }

  /**
   * 删除
   */
  async delete(idList) {
    await this.adjustmentRepository.delete(idList);
  }

  async isExistKey(data) {
    const {
      machineCode,
      // adjustmentName
    } = data;

    const result = await this.adjustmentRepository.findOne({ where: { machineCode } });
    if (result) throw new ApiException(10045);
  }

  /**
   * 详情
   */
  async info(data) {
    const machine: any = await this.adjustmentRepository.findOne({
      where: { machineCode: data.machineCode },
    });

    if (isEmpty(machine)) {
      return null;
    }

    const { adjustmentProcessCode, machineUnitCode } = machine;

    // console.log('machine', machine);

    const adjustmentRows = await this.adjustmentProcessRepository.findOne({
      where: { adjustmentProcessCode },
    });

    // console.log('adjustmentRows', adjustmentRows);

    const btnOptionsList = [];

    const adjustmentBtnList = adjustmentRows.adjustmentBtn?.split(',');

    if (adjustmentBtnList && adjustmentBtnList.length) {
      for (const item of adjustmentBtnList) {
        const result = await this.interfaceBtnRepository.findOne({
          where: { btnCode: item },
        });

        if (result && result.btnJson) {
          btnOptionsList.push(JSON.parse(result.btnJson));
        }
      }
    }

    const adjustmentInterfaceList = adjustmentRows.adjustmentInterface?.split(',');

    const adjustingOptions = {};

    if (adjustmentInterfaceList && adjustmentInterfaceList.length) {
      for (const item of adjustmentInterfaceList) {
        const result = await this.interfaceRepository.findOne({
          where: { interfaceCode: item },
        });

        if (result && result.interfaceJson) {
          adjustingOptions[item] = JSON.parse(result.interfaceJson);
        }
      }
    }

    let adjustingSettingList = [];

    if (machineUnitCode) {
      const machineUnit = await this.machineUnitRepository.findOne({
        where: { machineUnitCode },
      });

      if (machineUnit && machineUnit.machineUnitJson) {
        adjustingSettingList = JSON.parse(machineUnit.machineUnitJson);
      }
    }

    return {
      ...machine,
      adjustingOptions,
      btnOptions: {
        type: 'btn',
        labelZh: '调机按钮',
        labelEn: 'Testing Button',
        labelRu: 'Кнопка настройки устройства',
        list: btnOptionsList,
      },
      adjustingSetting: {
        type: 'adjustingSetting',
        labelZh: '调机参数设定',
        labelEn: 'Testing Parameters Settings',
        labelRu: 'Установка параметров настройки устройства',
        contentType: 'tab',
        // saveParameters: true,
        list: adjustingSettingList,
      },
    };
  }
}
